<template>
  <el-row :gutter="20">
    <!-- 用例集树 -->
    <el-col :span="5" :xs="24">
      <ContentWrap class="h-1/1">
        <TestboxTree ref="treeRef" @node-click="handleDeptNodeClick" @refresh="getList" />
      </ContentWrap>
    </el-col>
    <el-col :span="19" :xs="24">
      <!-- 搜索 -->
      <ContentWrap>
        <el-form class="-mb-15px" :model="queryParams" ref="queryFormRef" :inline="true">
          <el-form-item label="用例名称" prop="name">
            <el-input v-model="queryParams.name" placeholder="请输入用例名称" clearable @keyup.enter="handleQuery"
              class="!w-240px" />
          </el-form-item>
          <el-form-item label="用例标识" prop="logo">
            <el-input v-model="queryParams.logo" placeholder="请输入用例标识" clearable @keyup.enter="handleQuery"
              class="!w-240px" />
          </el-form-item>
          <el-form-item label="类型" prop="type">
            <el-select v-model="queryParams.type" placeholder="类型" clearable class="!w-240px">
              <el-option v-for="item in getIntDictOptions(DICT_TYPE.TEST_TYPE)" :key="item.value" :label="item.label"
                :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button @click="handleQuery">
              <Icon icon="ep:search" />搜索
            </el-button>
            <el-button @click="resetQuery">
              <Icon icon="ep:refresh" />重置
            </el-button>
            <el-button type="primary" plain @click="openForm('create')" v-if="editePermission">
              <Icon icon="ep:plus" /> 新增
            </el-button>
          </el-form-item>
        </el-form>
      </ContentWrap>
      <ContentWrap>
        <el-table v-loading="loading" :data="list">
          <el-table-column align="center" label="序号" type="index" width="80" />
          <el-table-column label="用例名称" align="center" prop="name" width="200" :show-overflow-tooltip="true" />
          <el-table-column label="用例标识" align="center" prop="logo" :show-overflow-tooltip="true" />
          <el-table-column label="测试类型" align="center" prop="type" :show-overflow-tooltip="true">
            <template #default="scope">
              <dict-tag :type="DICT_TYPE.TEST_TYPE" :value="scope.row.type" />
            </template>
          </el-table-column>
          <el-table-column label="创建人" align="center" prop="creatorName" :show-overflow-tooltip="true" />
          <el-table-column label="创建时间" align="center" prop="createTime" :formatter="dateFormatter" width="180" />
          <el-table-column label="操作" align="center" width="260">
            <template #default="scope">
              <div class="flex items-center justify-center">
                <el-button type="primary" link @click="openForm('update', scope.row.id)" v-if="editePermission">
                  编辑
                </el-button>
                <el-button type="primary" link @click="openForm('view', scope.row.id)" v-if="viewPermission">
                  查看
                </el-button>
                <el-button type="primary" link @click="openForm('create', scope.row.id)" v-if="editePermission">
                  复制
                </el-button>
                <el-button link type="danger" @click="handleDelete(scope.row.id)" v-if="editePermission">
                  删除
                </el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
        <Pagination :total="total" v-model:page="queryParams.pageNo" v-model:limit="queryParams.pageSize"
          @pagination="getList" />
      </ContentWrap>
    </el-col>
  </el-row>
  <!-- 用例表单弹窗：添加/修改 -->
  <useCaseForm ref="formRef" @success="getList" />
</template>
<script lang="ts" setup>
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
import { dateFormatter } from '@/utils/formatTime'
import * as UseCaseApi from '@/api/usecase'
import TestboxTree from './TestboxTree.vue'
import useCaseForm from './useCaseForm.vue'

defineOptions({ name: 'UseCaseManage' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

import { useAppStore } from '@/store/modules/app'
const appStore = useAppStore()

let projectId = computed(() => appStore.getSelectProject)
const loading = ref(true) // 列表的加载中
const total = ref(0) // 列表的总页数
const list = ref([]) // 列表的数
const queryParams = reactive({
  projectId: projectId.value,
  pageNo: 1,
  pageSize: 10,
  name: '',
  logo: '',
  type: '',
  suite: '',
  parent: ''
})
const queryFormRef = ref() // 搜索的表单
const treeRef = ref()


watch(projectId, (newValue) => {
  queryParams.projectId = newValue
  getList()
  getTypeList()
  getProjectMemberRole()
})

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await UseCaseApi.getPage(queryParams)
    list.value = data.records
    total.value = data.total
    treeRef.value.getTree()
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields()
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id, projectId, suiteId)
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await UseCaseApi.deleteUseCase(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch { }
}

const suiteId = ref()
/** 处理部门被点击 */
const handleDeptNodeClick = async (row) => {
  suiteId.value = row.id
  queryParams.suite = row.id
  queryParams.parent = row.parent
  await getList()
}

const typeList = ref([]) // 测试类型列表
/** 加载测试类型列表 */
const getTypeList = async () => {
  typeList.value = await UseCaseApi.getTypeList()
}

const role = ref('')
const editePermission = computed(() => ['admin', 'testManager', 'tester'].includes(role.value))
const viewPermission = computed(() => ['admin', 'projectManager', 'developer', 'testManager', 'tester'].includes(role.value))
// 获取人员在项目中角色
const getProjectMemberRole = async () => {
  let data = await UseCaseApi.getProjectMemberRole({ projectId: projectId.value })
  role.value = data
}

/** 初始化 */
onMounted(() => {
  if (projectId.value) {
    getList()
    getTypeList()
    getProjectMemberRole()
  }
})
</script>
